#生产者消费者模拟
import threading
import random
import time
gMoney=1000
gLock=threading.Lock()
gTotalTimes=10
gTimes=0

class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gTimes
        while True:
            money=random.randint(100,1000)
            gLock.acquire()
            #在进行生产之前，先判断是否10次
            if gTimes>=10:
                gLock.release()
                break
            gMoney += money
            print("%s生产了%d元，剩余%d元"%(threading.current_thread(),money,gMoney))
            gTimes+=1
            gLock.release()
            time.sleep(0.5)

#在此处需要设置退出条件，否则就是死循环。
#现在设置退出条件是10次,那么退出之前要解锁，不然别的线程无法访问了。
class Consumer(threading.Thread):
    def run(self):
        global gMoney
        global gTimes
        while True:
            money=random.randint(100,1000)
            gLock.acquire()
            if gMoney>=money:
                gMoney-= money
                print("%s消费了%d元，剩余%d元"%(threading.current_thread(),money,gMoney))
            else:
                if gTimes>=gTotalTimes:
                    gLock.release()
                    break
                print("%s消费了%d元，剩余%d元，不足。" % (threading.current_thread(), money, gMoney))
            gLock.release()
            time.sleep(0.5)


def main():
     for x in range(5):
         t=Producer(name="生产者线程%d"%x)
         t.start()
     for x in range(3):
         t=Consumer(name="消费者线程%d"%x)
         t.start()
if __name__ == '__main__':
    main()